#!/usr/bin/env python
# coding:utf-8
import os, hashlib
import time, logging
import shutil

def md5sum(f_name):
    def read_chunks(fh):
        fh.seek(0)
        chunk = fh.read(8096)
        while chunk:
            yield chunk
            chunk = fh.read(8096)
        else:
            fh.seek(0)
    m = hashlib.md5()
    if isinstance(f_name, basestring) and os.path.exists(f_name): 
        with open(f_name, "rb") as fh:
            for chunk in read_chunks(fh):
                m.update(chunk)
    elif f_name.__class__.__name__ in ["StringIO", "StringO"] or isinstance(f_name, file): 
        for chunk in read_chunks(f_name):
            m.update(chunk)
    else:
        return ""
    return m.hexdigest()

def writetolog(logDir, logName, logLevel, MSG):
    if not os.path.exists(logDir):
        os.makedirs(logDir)
    DATE = time.strftime("%Y-%m-%d")
    logFile = os.path.join(logDir, logName + "-" + DATE + ".log")
    logging.basicConfig(filename=logFile,
        format='%(asctime)s,%(levelname)s,%(message)s',
        datefmt='%Y-%m-%d %H:%M:%S',
        level=logging.DEBUG)
    if logLevel == "DEBUG":
        logging.debug(MSG)
    elif logLevel == "INFO":
        logging.info(MSG)
    elif logLevel == "WARN":
        logging.warn(MSG)
    elif logLevel == "ERROR":
        logging.error(MSG)
    elif logLevel == "FATAL":
        logging.fatal(MSG)
    else:
        f = open(logFile, 'a+')
        print >> f, time.strftime("%Y-%m-%d %H:%M:%S") + ",FATAL,Unknow loglevel."
        f.close()

def listFile(dirName):
    fileList = []
    for fpath, dirs, fs in os.walk(os.path.join(dirName)):
        for f in fs:
            f = os.path.join(fpath, f)
            fileList.append(f)
    return fileList

def cpDirCover(srcDir, dstDir):
    srcList = listFile(srcDir)
    for f in srcList:
        dstFile = os.path.join(dstDir, f[len(srcDir) + 1:])
        if not os.path.exists(os.path.dirname(dstFile)):
            os.makedirs(os.path.dirname(dstFile))
        shutil.copy(f, dstFile)

def cpDirUncover(srcDir, dstDir):
    srcList = listFile(srcDir)
    for f in srcList:
        dstFile = os.path.join(dstDir, f[len(srcDir) + 1:])
        if not os.path.exists(dstFile):
            if not os.path.exists(os.path.dirname(dstFile)):
                os.makedirs(os.path.dirname(dstFile))
            shutil.copy(f, dstFile)

if __name__ == '__main__':
    pass

